/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.cruisewatcher;

import com.intellij.openapi.diagnostic.Logger;

import java.net.Authenticator;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AllBuildsWatcher extends Thread {
    private Logger logger = Logger.getInstance(getClass().getName());
    private boolean keepRunning = true;
    private Map map = new HashMap();
    private int pauseCount = 0;
    private final CruiseWatcherSettings settings;

    public AllBuildsWatcher(CruiseWatcherSettings cruiseWatcherSettings) {
        this.settings = cruiseWatcherSettings;
    }

    public void stopRunning() {
        keepRunning = false;
    }

    public void reset() {
        map.clear();
    }

    public void pauseDisplay() {
        pauseCount++;
        logger.info("pause ( " + pauseCount + ")");
    }

    public void resumeDisplay() {
        pauseCount--;
        logger.info("resume ( " + pauseCount + ")");
    }

    public void run() {
        while (keepRunning) {
            try {
                int refresh = Math.max(1, settings.refreshInterval);
                sleep(refresh * 60000);
                if (pauseCount == 0 && settings.baseUrl != null && settings.baseUrl.trim().length() > 0) {
                    if (settings.disableProxy) {
                        System.setProperty("http.nonProxyHosts", new URL(settings.baseUrl).getHost());
                        Authenticator.setDefault(null);
                    }
                    List builds = settings.getBuilds();
                    for (Iterator iterator = builds.iterator(); iterator.hasNext();) {
                        CruiseBuild cruiseBuild = (CruiseBuild) iterator.next();
                        logger.info("Processing : " + cruiseBuild.getName());
                        CruiseBuildWatcher cruiseBuildWatcher = (CruiseBuildWatcher) map.get(cruiseBuild);
                        if (cruiseBuildWatcher == null) {
                            cruiseBuildWatcher = new CruiseBuildWatcher(cruiseBuild, settings);
                            map.put(cruiseBuild, cruiseBuildWatcher);
                        }
                        cruiseBuildWatcher.watch();
                    }
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }
}
